<template>
  <scroll-view class="drug-bg" scroll-y="true">
    <view class="drug-title">药品查询</view>
    <view class="search-bar">
      <!-- 使用uni-icon组件替代内联SVG -->
     <uni-icons class="search-icon" type="search" size="40rpx" color="#00CC71"></uni-icons>
      <input 
        type="text" 
        placeholder="输入药名/条码/公司搜索药品" 
        class="search-input"
        v-model="keyword" @input="onInputChange"
      />
    </view>
    <view class="drug-list">
      <view class="drug-card" v-for="item in drugList" :key="item.id">
        <view class="card-bar"></view>
        <view class="card-main">
          <view class="card-row">
            <text class="drug-name">{{ item.name }}</text>
            <text class="drug-type" :class="item.typeClass">{{ item.type }}</text>
          </view>
          <view class="card-info">规格：<text class="info-value">{{ item.spec }}</text></view>
          <view class="card-info">国药准字：<text class="info-value">{{ item.signid }}</text></view>
          <view class="card-info">生产单位：<text class="info-value">{{ item.pro_unit }}</text></view>
        </view>
      </view>
    </view>
  </scroll-view>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'

// 使用全局类型定义

// 变量声明
const keyword = ref('')
const drugList = ref({})
const loading = ref(false)
const page = ref(1)
const pagenum = ref(10)
let debounceTimer: any = null;

function onInputChange(e) {
  keyword.value = typeof e === 'string' ? e : e.detail.value;
  if (debounceTimer) clearTimeout(debounceTimer);
  debounceTimer = setTimeout(() => {
    if (keyword.value.trim() === '') {
      fetchDrugs();
    } else {
      searchDrugsByName();
    }
  }, 300);
}

function getNameNodes(name: string) {
  if (!keyword.value.trim()) return [{ type: 'text', text: name }];
  const reg = new RegExp(keyword.value, 'gi');
  const nodes: any[] = [];
  let lastIndex = 0;
  let match;
  while ((match = reg.exec(name)) !== null) {
    if (match.index > lastIndex) {
      nodes.push({ type: 'text', text: name.slice(lastIndex, match.index) });
    }
    nodes.push({
      name: 'span',
      attrs: { class: 'highlight' },
      children: [{ type: 'text', text: match[0] }]
    });
    lastIndex = match.index + match[0].length;
  }
  if (lastIndex < name.length) {
    nodes.push({ type: 'text', text: name.slice(lastIndex) });
  }
  return nodes;
}

function fetchDrugs() {
  loading.value = true;
  uni.request({
    url: `http://localhost:3010/search/drugs/list?page=${page.value}&pagenum=${pagenum.value}`,
    method: 'GET',
	header: {
	  'content-type': 'application/x-www-form-urlencoded',
	  'Authorization': 'Bearer ' + uni.getStorageSync('token')
	},
    success: (res) => {
      loading.value = true;
      if (res.data && res.data.code === 200) {
        drugList.value = (res.data.data.result || []).map((item: any) => ({
          id: item.id,
          name: item.name,
          type: item.type,
          typeClass: getTypeClass(item.type),
          spec: item.spec,
          signid: item.signid,
          pro_unit: item.pro_unit
        }))
      } else {
        uni.showToast({ title: res.data.msg || '获取药品失败', icon: 'none' })
      }
    },
    fail: () => {
      loading.value = false;
      uni.showToast({ title: '网络请求失败', icon: 'none' })
    }
  })
}

function searchDrugsByName() {
  loading.value = true;
  uni.request({
    url: 'http://localhost:3010/search/drugs',
    method: 'POST',
    header: {
      'content-type': 'application/x-www-form-urlencoded',
      'Authorization': 'Bearer ' + uni.getStorageSync('token')
    },
    data: {
      name1: keyword.value,
      page: page.value,
      pagenum: pagenum.value
    },
    success: (res) => {
      console.log(res);
      loading.value = false;
      if (res.data && res.data.code === 200) {
        drugList.value = (res.data.data.result || []).map((item: any) => ({
          id: item.id,
          name: item.name,
          type: item.type,
          typeClass: getTypeClass(item.type),
          spec: item.spec,
          signid: item.signid,
          pro_unit: item.pro_unit
        }))
      } else {
        uni.showToast({ title: res.data.msg || '获取药品失败', icon: 'none' })
      }
    },
    fail: () => {
      loading.value = false;
      uni.showToast({ title: '网络请求失败', icon: 'none' })
    }
  })
}

function onSearch() {
  if (keyword.value.trim() === '') {
    fetchDrugs(); // 关键字为空时恢复商品列表
  } else {
    searchDrugsByName();
  }
}

function getTypeClass(type: string) {
  if (type.includes('片')) return 'type-pill'
  if (type.includes('注射')) return 'type-inject'
  if (type.includes('原料')) return 'type-raw'
  return ''
}

onMounted(() => {
  fetchDrugs()
})
</script>

<style scoped>
.drug-bg {
  min-height: 100vh;
  background: #e5e5e5;
  padding-bottom: 20rpx;
  padding-top: 90rpx;
  box-sizing: border-box;
}
.drug-title {
  text-align: center;
  font-size: 36rpx;
  font-weight: bold;
  color: #444;
  margin: 32rpx 0 24rpx 0;
}
.search-bar {
  margin: 0 32rpx 32rpx 32rpx;
  background: #fff;
  border-radius: 16rpx;
  box-shadow: 0 4rpx 16rpx #b2ffe0;
  display: flex;
  align-items: center;
  padding: 0 24rpx;
  height: 64rpx;
}
.search-icon {
  width: 36rpx;
  height: 36rpx;
  margin-right: 12rpx;
}
.search-input {
  flex: 1;
  border: none;
  outline: none;
  font-size: 26rpx;
  color: #888;
  background: transparent;
}
.drug-list {
  margin-top: 0;
}
.drug-card {
  display: flex;
  align-items: stretch;
  background: #fff;
  border-radius: 24rpx;
  margin: 0 32rpx 24rpx 32rpx;
  box-shadow: 0 2rpx 8rpx #e0f7ef;
  position: relative;
  padding: 0;
}
.card-bar {
  width: 8rpx;
  background: #1ed11c;
  border-radius: 8rpx 0 0 8rpx;
  margin-right: 18rpx;
}
.card-main {
  flex: 1;
  padding: 24rpx 0 24rpx 0;
  display: flex;
  flex-direction: column;
  justify-content: center;
}
.card-row {
  display: flex;
  align-items: center;
  margin-bottom: 8rpx;
}
.drug-name {
  font-size: 28rpx;
  font-weight: bold;
  color: #222;
  margin-right: 12rpx;
}
.drug-type {
  font-size: 22rpx;
  padding: 2rpx 16rpx;
  border-radius: 16rpx;
  font-weight: bold;
  margin-left: 0;
}
.type-pill {
  background: #16e39a;
  color: #fff;
}
.type-inject {
  background: #1ed11c;
  color: #fff;
}
.type-raw {
  background: #b2e600;
  color: #fff;
}
.card-info {
  font-size: 24rpx;
  color: #888;
  margin-bottom: 2rpx;
  display: flex;
  align-items: center;
}
.info-value {
  color: #666;
  margin-left: 4rpx;
}
.card-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 64rpx;
  min-width: 64rpx;
  border-radius: 0 24rpx 24rpx 0;
  background: none;
}
.btn-icon {
  width: 38rpx;
  height: 38rpx;
  background: #16e39a;
  border-radius: 50%;
  padding: 8rpx;
}
.highlight {
  color: #16e39a;
  background: #e6fff3;
  font-weight: bold;
  border-radius: 4rpx;
  padding: 0 2rpx;
}
</style>